<?php

namespace App\Http\Middleware;

use App\Model\Admin;
use Closure;
class IsLogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(session()->get('LoginAdmin')){

            $LoginAdmin = !empty(session()->get('LoginAdmin')) ? session()->get('LoginAdmin') : '';

            $adminList = Admin::all();

            $adminid = 0;

            foreach($adminList as $item)
            {
                $val = md5($item['id'].$item['salt']);

                if($LoginAdmin == $val)
                {
                    $adminid = $item['id'];
                    break;
                }
            }

            $admin = Admin::find($adminid);

            $admin = !empty($admin) ? $admin : [];

            if(!$admin)
            {
                // 清空session
                session()->flush();
                return redirect('admin/login')->withErrors('非法登录','admin') ->withInput();
            }

            if($admin['state'] != 1)
            {
                // 清空session
                session()->flush();
                return redirect('admin/login')->withErrors('管理员已禁用','admin') ->withInput();
            }

            return $next($request);
        }else{
            return redirect('admin/login')->withErrors('您还未登录，请先登录！','admin') ->withInput();
        }
    }
}
